﻿using System;
using System.Collections.Generic;
using System.Linq;
using EzDesk.Apps.Model.ProjectModule;
using EzDesk.Core.Interface;
using EzDesk.Core.Model;
using EzDesk.Core.ServiceImpl.Services;
using EzDesk.Utility;

namespace EzDesk.ServiceHost.ViewModels
{
    public static class WorkitemEx 
    {
        static private readonly ICoreAppService _coreAppService = new CoreAppService();

        public static Workitem PopulateCreatorNameAndOwnerName(this Workitem workitem)
        {
            if (workitem.OwnerId.HasValue)
                workitem.OwnerName = _coreAppService.GetSimpleUserById(workitem.OwnerId.Value).Name;

            workitem.CreatorName = _coreAppService.GetSimpleUserById(workitem.CreatorId).Name;
            return workitem;
        }

        public static ICollection<Workitem> PopulateCreatorNameAndOwnerNames(this ICollection<Workitem> workitems)
        {
            var userIds = new List<Guid>();
            workitems.Foreach(p =>
                                  {
                                      if (p.OwnerId.HasValue)
                                      {
                                          if (userIds.IndexOf(p.OwnerId.Value) < 0)
                                          {
                                              userIds.Add(p.OwnerId.Value);
                                          }
                                      }
                                      if (userIds.IndexOf(p.CreatorId) < 0)
                                      {
                                          userIds.Add(p.CreatorId);
                                      }
                                  }
                );
            var allUsers = _coreAppService.GetSimpleUserInfos(userIds.Join(","));

            workitems.Foreach(p =>
                                  {
                                      if (p.OwnerId.HasValue)
                                      {
                                          p.OwnerName = allUsers.FirstOrDefault(u => u.Id == p.OwnerId.Value).Name;
                                      }
                                      p.CreatorName = allUsers.FirstOrDefault(u => u.Id == p.CreatorId).Name;
                                  }
                                  );
            return workitems;
        }

    }
}
